<template>
	<view>
		<!-- #ifdef H5 -->
		<uni-nav-bar left-icon="back" @clickLeft="back" :border="false" title="分享海报"></uni-nav-bar>
		<!-- #endif -->
		<!-- 画布 -->
		<canvas
			canvas-id="mycanvas"
			style="position:fixed;top:-10000px;right:-10000px;background: red;"
			:style="'width:' + canvas_width + 'px' + ';height:' + canvas_height + 'px'"
		></canvas>
		<!-- 轮播 -->
		<view class="banner">
			<swiper class="banner_swiper" circular="true" previous-margin="66rpx" next-margin="49rpx" :current="current_index" @change="change">
				<swiper-item v-for="(item, index) in banner_list" :key="index" @longtap="saveBtn">
					<view class="banner_swiper_item">
						<image class="banner_swiper_item_pic" :class="index == current_index ? 'banner_swiper_item_active' : ''" :src="item.pic" />
					</view>
				</swiper-item>
			</swiper>
		</view>
		<!-- 保存按钮 -->
		<view class="saveBtn" @click="saveBtn">保存海报</view>
		<!-- H5弹窗 -->
		<uni-popup ref="popup" type="center" :animation="false">
			<view class="popup">
				<img class="popup_pic" :src="tmp_pic" />
				<view class="popup_text">长按保存图片</view>
			</view>
		</uni-popup>
		<!-- 自定义加载 -->
		<MyLoading :loading="loading" type="4" animation_updown="true"></MyLoading>
	</view>
</template>

<script>
import Route from '../../utils/route.js';
import MyLoading from '@/components/my-loading/my-loading.vue';
export default {
	components: {
		MyLoading,
	},
	data() {
		return {
			// 自定义加载动画
			loading: true,
			// 画布
			canvas_width: 375,
			canvas_height: 563,
			// 二维码
			QRcode: '',
			// 二维码大小
			QRcode_size: 81,
			// 轮播
			current_index: 0,
			banner_list: [],
			// 海报
			tmp_list: [],
			tmp_pic: ''
		};
	},
	async onLoad() {
		this.loading = true;
		// 获取二维码
		await this.getPoster_QRcode_wechat();
		// 获取海报列表
		await this.getPosterList();
		// 将网络路径转化tmp路径
		await this.format();
		this.loading = false;
	},
	methods: {
		// 获取小程序二维码
		async getPoster_QRcode_wechat(){
			let res = await Route.poster_QRcode_wechat({
				uid:uni.getStorageSync('userInfo').uid
			});
			this.QRcode = res.info;
		},
		// 获取海报数据
		async getPosterList(){
			let res = await Route.poster_list();
			this.banner_list = res.list;
		},
		// 返回
		back() {
			uni.navigateBack();
		},
		// 轮播
		change(e) {
			this.current_index = e.detail.current;
		},
		/**
		 * 将网络路径转化tmp路径
		 * @param {string} e tmp图片路径
		 */
		down(e) {
			return new Promise((resolve, reject) => {
				// 获取网络图片路径  会牵涉跨域 那么则需要从服务器中代理
				uni.downloadFile({
					url: e,
					success: res => {
						if (res.statusCode === 200) {
							resolve(res.tempFilePath);
						} else {
							reject('下载失败');
						}
					},
					fail: reject
				});
			});
		},
		/**
		 * 将网络路径转化tmp路径
		 * @param {string} e tmp图片路径
		 */
		temp(e) {
			return new Promise((resolve, reject) => {
				uni.getImageInfo({
					src: e,
					success: function(res) {
						resolve(res.path);
					}
				});
			});
		},
		// 格式化tmp
		async format() {
			let copy = JSON.stringify(this.banner_list)
			this.tmp_list = JSON.parse(copy);;
			// #ifdef MP-WEIXIN
			this.QRcode = await this.temp(this.QRcode);
			for (let i = 0; i < this.tmp_list.length; i++) {
				// arr.push(await this.carete(await this.temp(this.banner_list[i]))); //刚进来渲染所有图片
				this.tmp_list[i].pic = await this.temp(this.tmp_list[i].pic); //点击保存时候渲染
			}
			// #endif
			// #ifdef H5
			this.QRcode = await this.down(this.QRcode);
			for (let i = 0; i < this.tmp_list.length; i++) {
				// arr.push(await this.carete(await this.temp(this.banner_list[i]))); 刚进来渲染所有图片
				this.tmp_list[i].pic = await this.down(this.tmp_list[i].pic);//点击保存时候渲染
			}
			// #endif
		},
		/**
		 * 合成海报
		 * @param {string} e tmp图片路径
		 * @param {number} x 二维码X坐标
		 * @param {number} y 二维码y坐标
		 */
		carete(tmp_pic, QRcode_x, QRcode_y) {
			return new Promise((resolve, reject) => {
				var that = this;
				var context = wx.createCanvasContext('mycanvas');
				// 将主图画到画布
				context.drawImage(tmp_pic, 0, 0, that.canvas_width, that.canvas_height); // drawImage(图片路径,x,y,绘制图像的宽度，绘制图像的高度,二维码的宽,高)
				//二维码背景填充颜色
				var x = QRcode_x;
				var y = QRcode_y;
				var h = that.QRcode_size;
				var w = that.QRcode_size;
				var r = 10;
				// 开始画白色背景
				context.beginPath();
				// 左上弧线
				context.arc(x + r, y + r, r, 1 * Math.PI, 1.5 * Math.PI);
				// 左直线
				context.moveTo(x, y + r);
				context.lineTo(x, y + h - r);
				// 左下弧线
				context.arc(x + r, y + h - r, r, 0.5 * Math.PI, 1 * Math.PI);
				// 下直线
				context.lineTo(x + r, y + h);
				context.lineTo(x + w - r, y + h);
				// 右下弧线
				context.arc(x + w - r, y + h - r, r, 0 * Math.PI, 0.5 * Math.PI);
				// 右直线
				context.lineTo(x + w, y + h - r);
				context.lineTo(x + w, y + r);
				// 右上弧线
				context.arc(x + w - r, y + r, r, 1.5 * Math.PI, 2 * Math.PI);
				// 上直线
				context.lineTo(x + w - r, y);
				context.lineTo(x + r, y);
				context.setFillStyle('white');
				context.fill();
				// 将二维码画到画布
				context.drawImage(this.QRcode, QRcode_x, QRcode_y, that.QRcode_size, that.QRcode_size); // drawImage(图片路径,x,y,绘制图像的宽度，绘制图像的高度,二维码的宽,高)
				// 设置文字
				// context.setFontSize(15); // 字号
				// context.setFillStyle('#000'); // 颜色
				// context.fillText('扫码购电影票', that.canvas_width - 126, that.canvas_width + 125); // （文字，x，y）
				// context.setFillStyle('#fd0202'); // 颜色
				// context.fillText('立享六折优惠', that.canvas_width - 126, that.canvas_width + 145); // （文字，x，y）
				//保存之前的画布设置
				context.save();
				// draw方法 把以上内容画到 canvas 中。
				context.draw(true, ret => {
					// 保存canvas为图片 在H5平台下，tempFilePath 为 base64, // 图片提示跨域 H5保存base64失败，APP端正常输出临时路径
					uni.canvasToTempFilePath({
						width: that.canvas_width, //画布宽度（默认为canvas宽度-x）
						height: that.canvas_height, //画布高度（默认为canvas高度-y）
						destWidth: that.canvas_width * 2, //输出图片宽度（默认为 width * 屏幕像素密度）
						destHeight: that.canvas_height * 2, //输出图片高度（默认为 height * 屏幕像素密度）
						canvasId: 'mycanvas',
						success:  async (res)=> {
							resolve(res.tempFilePath);
						},
						fail: function(res) {
						}
					});
				});
			});
		},

		//保存海报
		async saveBtn() {
			uni.showLoading()
			let info = this.tmp_list[this.current_index];
			let poster = await this.carete(info.pic, info.QRcode_x, info.QRcode_y);
			//#ifdef MP-WEIXIN
			uni.saveImageToPhotosAlbum({
				filePath: poster,
				// 授权成功
				success: function(res) {
					uni.showToast({
						title: '保存成功,请到相册中查看',
						icon: 'none'
					});
				},
				// 授权拒绝
				fail: function() {
					uni.showModal({
						content: '检测到您未打开相册权限，是否去设置打开？',
						confirmText: '确认',
						cancelText: '取消',
						success: res => {
							if (res.confirm) {
								uni.openSetting({
									success: res => {
										uni.showToast({
											title: '请重新点击保存图片～',
											icon: 'none'
										});
									}
								});
							} else {
								uni.showToast({
									title: '请打开权限功能重试',
									icon: 'none'
								});
							}
						}
					});
				}
			});
			// #endif
			//#ifdef H5
			this.tmp_pic = poster;
			this.$refs.popup.open();
			
			// #endif
		}
	}
};
</script>

<style lang="scss">
// 轮播
.banner {
	margin-top: 33rpx;
	position: relative;
	&_swiper {
		height: 950rpx;
		display: flex;
		align-items: center;
		&_item {
			width: 633rpx;
			height: 950rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			&_pic {
				width: 600rpx;
				height: 900rpx;
				display: flex;
			}

			&_active {
				width: 633rpx;
				height: 950rpx;
				// animation: change 0.5s;
				// animation-fill-mode: forwards;
			}
			@keyframes change {
				from {
					width: 600rpx;
					height: 900rpx;
				}
				to {
					width: 633rpx;
					height: 950rpx;
				}
			}
		}
	}
}
// 保存按钮
.saveBtn {
	font-size: $uni-font-size-base;
	background: $template-background;
	color: #fff;
	width: 333rpx;
	height: 81rpx;
	line-height: 81rpx;
	text-align: center;
	border-radius: 40rpx;
	margin: 0 auto;
	margin-top: 81rpx;
	position: absolute;
	left: 0;
	right: 0;
	margin: auto;
	bottom: 49rpx;
}
.popup {
	display: flex;
	flex-direction: column;
	align-items: center;
	background: #fff;
	padding: 33rpx;
	border-radius: 13rpx;
	&_pic {
		width: 600rpx;
		height: 900rpx;
	}
	&_text {
		font-size: 49rpx;
		font-weight: 600;
		margin-top: 33rpx;
		color: $template-background;
	}
}
</style>
